<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app"></div>
    <button id="btn">打印</button>
    <button id="btn1">取消</button>
</body>
<script src="./js/underscore-min.js"></script>
<script>
    // var btn = document.getElementById('btn');
    // var btn1 = document.getElementById('btn1');
    let debounced = debounce(handleClick, 1000)
    btn.onmousemove = debounced;
    btn1.onclick = debounced.cancel;
 
    function handleClick(e) {
        console.log (this, 111,e);

        return  e
    }
    // 防抖函数
    function debounce(callback, awit, flag) {
        let timer = null,result;
        let  debounced = function () {
            if (timer) {
                // 一开始进来先清除定时器
                clearTimeout(timer)
            }
            if (flag) {
                //判断是否立即执行
                let callNow = !timer;
               timer = setTimeout(() => {
                   //等待的时间结束将timer重新设置为空
                  timer = null ;  
                }, awit);
                if(callNow){
                    //立即执行
                    result = callback.apply(this, arguments);
                }
            } else {
                timer = setTimeout(() => {
                    callback.apply(this, arguments);
                }, awit);
            }
            console.log(timer,"++++");
            return result;
        }
        //取消本次操作
        debounced.cancel=function(){
            clearTimeout(timer);
            timer = null; // 解决内存泄漏问题
        }
        return debounced;
    }


//    function debounce (callback,awit,flag){
//        let timer = null,result;
//        let timeObj ={count:60000,time:1599408000000};
//        let week = 1000 * 60 * 60 * 24 * 7;
//        console.log(week);
//        if(!timeObj){
//            localStorage.setItem('timeObj',JSON.stringify(timeObj));
//         }
//         else if(1600012800000-timeObj.time === week){
//            localStorage.setItem('timeObj',JSON.stringify({count:timeObj.count+10000,time:Date.now()}));
//            timeObj = {count:timeObj.count+10000,time:Date.now()};          
//         }
//        let debounced = function (...args){
//            if(timer) clearTimeout(timer);
//            if(flag){
//                let callNow = !timer;
//                timer = setTimeout(()=>{
//                    timer = null;
//                },awit);
//                if(callNow){
//                 result = callback.apply(this,args)
//                }
//            }else {
//                timer = setTimeout(()=>{
//                    callback.apply(this,args)
//                },awit)
//            }
//            return result;
//        }
//        debounced.cancel = function(){
//             clearTimeout (timer);
//             timer = null;
//        } ;
//        return debounced;
//    }
</script>

</html>